/*
 * @Description: 抓取vova平台数据
 * @Author: zhangzhengzhe
 * @LastEditors: Please set LastEditors
 * @Date: 2019-03-22 11:50:23
 * @LastEditTime: 2019-03-22 13:03:04
 */
const puppeteer = require("puppeteer");
const fs = require("fs");
const isTrue = true;
const myApp = async () => {
  const width = 1360
  const height = 726
  const browser = await puppeteer.launch({
    headless: false, // 开启界面
    devtools: true,  // 开启开发者控制台
    // slowMo: 250
  });
  const page = await browser.newPage();
  await page.setViewport({
        width: width,
        height: height
  });
  await page.on('dialog', async dialog => {
    await dialog.dismiss();
    // await browser.close();
  });
  await page.setDefaultNavigationTimeout(0);
  // await page.goto("http://merchant.vova.com.hk", { waitUntil: 'load' });
  // await page.click(".login-page.link");
  await page.goto("http://merchant.vova.com.hk/index.php?q=admin/main/index/login", { waitUntil: 'load' });
  // 监听console输出
  page.on("console", msg => {
    for (let i = 0; i < msg.args.length; ++i)
      console.log(`${i}: ${msg.args[i]}`);
  });
  // 登录
  await page.type("#inputEmail", "vbshuqw@hotmail.com");
  await page.type("#inputPassword", "pzwg@123456STK");
  await page.click("#btn_submit");
  await page.waitFor(2000);
  // 进入商品列表
  await page.goto("http://merchant.vova.com.hk/index.php?q=admin/main/product/index&perPage=100");
  await page.waitFor(2000);
  //  这是个坑,因为此id是不定时弹出,若没有弹出此事件不执行,导致evalute无法执行
  // await page.click("#
  //
  // ");
  const pordlist = await page.evaluate(async () => {
    const $ = window.$
    const listArr = [];
    let type = "";
    const selectListArr = [];
    // 需要选中的id
    const selected = ["Albania", "Angola", "Antigua and Barbuda", "Aruba"];
    const trList = $("#prodlist-table tbody tr");
    // const modifySaleCategory = $("#modifySaleCategory");
    const popFeedbackModal = $("#pop-feedback-modal");
    const popNoticeModal =  $("#pop-notice-modal");
    if (popNoticeModal.is(":visible")) {
        $(".btn.btn-secondary.dismiss").click();
    }
    if (popFeedbackModal && popFeedbackModal.is(':hidden')) {
      trList.each((index, item) => {
        let tds = $(item).find("td")
        listArr.push({
          goods_src: tds.eq(0).find("img").attr('src'),
          goods_name: tds.eq(2).text(),
          parent_sku: tds.eq(3).val(),
          other_arr : tds.eq(4).text() === '无' ? 0 : 1,
          collect_quantity: tds.eq(5).text(),
          sales_volume: tds.eq(6).text(),
          variable: tds.eq(7).text(),
          original_shop_price: tds.eq(9).find("input").val(),
          original_shipping_fee: tds.eq(10).find("input").val(),
          original_storage: tds.eq(11).find("input").val(),
          sale_status: tds.eq(12).find("input").attr("checked") ? true : false,
          goods_id: $(item).attr("data-goods-id"),
          goods_sku: $(item).attr("data-goods_sku"),
          sku_id: $(item).attr("data-sku_id"),
          prom_type: $(item).attr("data-prom_type"),
          prom_type_for_show: $(item).attr("data-prom_type_for_show"),
          last_update_time:tds.eq(13).text(),
          upload_time: tds.eq(14).text(),
          illegal: tds.eq(15).text(),
          browse_view: tds.eq(16).text(),
          average_price: tds.eq(17).text(),
          goods_desc: tds.eq(18).find(".goods-desc").text()
        });
      });
      type = "list";
    } else {
      // await modifySaleCategory.click();
    //  克隆或不克隆页面
      trList.each((index, item) => {
        $(item).find("td").eq(6).attr("checked");
        let tds = $(item).find("td");
        listArr.push({
          goods_id: $(item).attr('data.goods-id'),
          goods_src: tds.eq(0).find("img").attr("src"),
          goods_href: tds.eq(1).find("a").attr("href"),
          goods_sku_price: tds.eq(2).text(),
          goods_is_normal: tds.eq(3).text() === "是" ? 1 : 0,
          goods_create_time: tds.eq(4).text(),
          goods_sale_status: tds.eq(6).attr("checked") ? true : false
        });
      })
      type = "not_clone";
    }
    return {
      type: type,
      list: listArr
    }
  })
  // 将文件写入json
  const writerStream = fs.createWriteStream( __dirname + "/js/prodlist_" + pordlist.type + "_list.json");
  writerStream.write(JSON.stringify(pordlist.list, undefined, 2), 'UTF8');
  writerStream.end();
  // 点击措施
  const clickMeasureFn = async () => {
    await page.click("button.dropdown-btn.btn.btn-sm.btn-primary");
    await page.waitFor(3000);
    await page.click("a.change-shipping-fee-btn");
    await page.waitFor(3000);
    await page.click(".SumoSelect");
    await page.waitFor(3000);
    await page.evaluate(() => {
      const $ = window.$;
      const selectListArr = [];
        // 需要选中的id
        const selected = [
          {
            name: "Albania",
            freight: 22.22
          }, {
            title: "Angola",
            freight: 11.22
          }, {
            title: "Antigua and Barbuda",
            freight: 33.55
          }, {
            title: "Aruba",
            freight: 60.56
          }];
        const lists = $(".optWrapper ul.options li");
        lists.map((index, item) => {
          let itemHtml = item.lastChild.innerHTML;
          selected.map(itemArr => {
            if (itemArr.title === itemHtml) {
              item.click();
              selectListArr.push(itemHtml);
            }
          });
        });
      $(".btn.btn-primary.add-btn.ml-3").click();
        const form = $(".form.format-form.edit-shipping ul li.shipping-item");
        form.map((index, item) => {
          let labelText = $(item).find("div.input-item").find("label").html().replace(":", "").trim();
          selected.map(val => {
            if (val.title === labelText) {
              $(item).find("div.input-item").find("input.form-control").val(val.freight);
            }
          })
        });
    });
  }
  clickMeasureFn();

  // 不可隆
  const notCloneFn = async () => {
    await page.evaluate(() => {
      const $ = window.$;
      const tableList = $("#prodlist-table tbody tr");
      console.log(tableList);
      tableList.map((index, item) => {
        $(item).find("td").eq(6).click();
      });
      $("#batch-not-clone").click();
    });
  }

  if (await page.$("#modifySaleCategory") && isTrue) {
    await page.click("#modifySaleCategory");
    await page.waitFor(3000);
    await page.goto("https://merchant.vova.com.hk/index.php?q=admin/main/cloneProduct/pendingCloneProductList&perPage=50");
    await page.waitFor(3000);
    await notCloneFn();
    await page.waitFor(3000);
    await page.goto("http://merchant.vova.com.hk/index.php?q=admin/main/product/index&perPage=100");
  }


  await page.waitForNavigation({waitUntil: "load"});
}
myApp();